﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using Openfree.Workflow.Common;
//using Openfree.Workflow.Workflow;
using Openfree.Framework.DataAccess;
using System.Text;

public partial class Controls_Activity_TaskPersonItem : WorkflowUserControl
{
    public EventHandler OnSelect;

    private bool m_ShowWorkTime = false;
    public bool ShowWorkTime
    {
        get { return m_ShowWorkTime; }
        set 
        {
            m_ShowWorkTime = value;
            hfShowWorkTime.Value = ""+value;
        }
    } 
    public string ShowTitle 
    {
        get { return this.showTitle.Text; }
        set {this.showTitle.Text = value;}
    }

    private bool m_IsReadOnly = false;
    public bool IsReadOnly
    {
        get { return m_IsReadOnly; }
        set { m_IsReadOnly = value; }
    }
    public string m_TableName = "PMS_TaskUser";

    private string cmdItemsText = @"SELECT T.*,A.Username,A.GroupCode,A.Mobile,B.OrgID,D.Subject as OrgName,C.CodeName as GroupName  FROM {0} T inner join PMS_User A on A.UserID = T.UserID 
                    left join T_OrgUser B on B.UserID = T.UserID 
                    left join  T_CodeConfig C on C.CodeValue=A.GroupCode  AND C.Category = '" + PMSCodeCategory.PMS_BMZB + @"' 
                    left join T_OrgTree D on D.OrgID=B.OrgID where 1=1 and T.UserType='" + PMSCodeCategory.UserWorker+ "' ";

    //(select CodeValue from T_CodeConfig where CodeValue=a.GroupCode And Category = '" + PMSCodeCategory.PMS_BMZB + @"') GroupCode,
    string sql = @"select a.*,
                        (select Username from T_User where UserID=a.UserID) Username,
                        (select top 1 OrgID from T_OrgUser where UserID=a.UserID) OrgID, 
                        (select (select top 1 Subject from T_OrgPool where OrgID=T_OrgUser.OrgID) OrgName
                            from T_OrgUser where UserID=a.UserID) OrgName,
						(select CodeName from T_CodeConfig where CodeValue=a.GroupCode  And Category = '" + PMSCodeCategory.PMS_BMZB + @"') GroupName
                        from PMS_User a ";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
        OnSelect += new EventHandler(btnShowSelectItem);
        UserSelect.OnUserSelectOk += new UserSelectEventHandler(btnSelectOk_Click);
    }
    public void InitData(string subkey, string subvalue)
    {
        InitData(subkey, subvalue,string.Empty);
    }

    public void InitData(string subkey, string subvalue,string groupcode)
    {
        string cmdtext = string.Format(cmdItemsText, m_TableName);
        if (!string.IsNullOrEmpty(subvalue))
            cmdtext += " AND T." + subkey + " = '" + subvalue + "' ";
        else
            cmdtext += " AND 1=2 ";
        if (!string.IsNullOrEmpty(groupcode))
        {
            cmdtext += " AND A.GroupCode='" + groupcode + "' ";
            this.UserSelect.SetTBGroupReadOnly(groupcode);
        }

        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, cmdtext, m_TableName);

        FillGirdView();
    }
    private void btnSelectOk_Click(object sender, EventArgs e)
    {
        DataTable dt = SessionManager.DataSet.Tables[UserSelect.m_Table];
        if(dt!=null &&dt.Rows.Count>0)
        {
            StringBuilder str = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                //if (dr["IsWorking"] !=null && dr["IsWorking"]!=DBNull.Value && Convert.ToInt32(dr["IsWorking"]) == UserStatus.Working) 
                //    continue; 
                if (SessionManager.DataSet.Tables[m_TableName].Select("UserID='" + dr["UserID"].ToString() + "'").Length > 0) continue;
                 
                DataRow _dr = SessionManager.DataSet.Tables[m_TableName].NewRow();
                _dr["TaskUserID"] = System.Guid.NewGuid();
                _dr["UserID"] = dr["UserID"];
                _dr["UserName"] = dr["UserName"];
                _dr["OrgName"] = dr["OrgName"];
                _dr["GroupCode"] = dr["GroupCode"];
                _dr["GroupName"] = dr["GroupName"];
                _dr["Mobile"] = dr["Mobile"]; 
                SessionManager.DataSet.Tables[m_TableName].Rows.Add(_dr);
            } 
        }
        FillGirdView();
    }
    public void AddSelectPerson(string personCode)
    {
        string sql = @"select a.*,
                        (select top 1 OrgID from T_OrgUser where UserID=a.UserID) OrgID, 
                        (select top 1 Subject from T_OrgTree where OrgID=(select OrgID from T_OrgUser where UserID=a.UserID)) OrgName,
						(select CodeName from T_CodeConfig where CodeValue=a.GroupCode  And Category = '" + PMSCodeCategory.PMS_BMZB + @"') GroupName
                        from PMS_User a where 1=1 and a.Barcode='" + personCode + "'";
        DataSet ds = PMSAccess.GetDataSet(this.Connection, sql);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        { 
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //if (dr["IsWorking"] != null && dr["IsWorking"] != DBNull.Value && Convert.ToInt32(dr["IsWorking"]) == UserStatus.Working)
                //    continue;  
                if (SessionManager.DataSet.Tables[m_TableName].Select("UserID='" + dr["UserID"].ToString() + "'").Length > 0) continue;
                DataRow _dr = SessionManager.DataSet.Tables[m_TableName].NewRow();
                _dr["TaskUserID"] = System.Guid.NewGuid();
                _dr["UserID"] = dr["UserID"];
                _dr["UserName"] = dr["UserName"];
                _dr["OrgName"] = dr["OrgName"];
                _dr["GroupCode"] = dr["GroupCode"];
                _dr["GroupName"] = dr["GroupName"];
                _dr["Mobile"] = dr["Mobile"];
                SessionManager.DataSet.Tables[m_TableName].Rows.Add(_dr);
            } 
            if (ds.Tables[0].Rows.Count > 0)
                FillGirdView();
        }
        else
        {
            Alert("您扫描的人员不存在，请确认人员编号是否正确！");
        }
    }


    /// <summary>
    /// 返回string.Empty为正确，返回非空字符串为错误提示信息
    /// </summary>
    /// <returns></returns>
    public string PreProcessSave()
    {
        DataTable dt = SessionManager.DataSet.Tables[m_TableName];

        if (gridView.Rows.Count == 0)
        {
            return "请选择人员！";
        }
        int n = -1;
        for (int i = 0; i < gridView.Rows.Count; i++)
        {
            n++;
            if (dt.Rows[n].RowState == DataRowState.Deleted)
            {
                i--;
                continue;
            }
            if (m_ShowWorkTime)
            {
                decimal count = 0;
                try
                {
                    count = Convert.ToDecimal((gridView.Rows[i].Cells[4].Controls[1] as TextBox).Text.Trim());
                }
                catch
                {
                    return "工分请输入整数或浮点数，其它值无效！";
                }
                dt.Rows[n]["WorkTime"] = count;
            }
            dt.Rows[n]["Description"] = (gridView.Rows[i].Cells[5].Controls[1] as TextBox).Text;
        }
        return string.Empty;
    }
    private void btnShowSelectItem(object sender, EventArgs e)
    {
        UserSelect.OnSelect(sender, e);
    }
    public void SetGroupReadOnly()
    {
        string code = string.Empty;
        if (SessionManager.DataSet.Tables[m_TableName].Rows.Count > 0)
        {
            foreach (DataRow dr in SessionManager.DataSet.Tables[m_TableName].Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                {
                    code = dr["GroupCode"].ToString(); 
                    break;
                }
            }
        }
        this.UserSelect.SetTBGroupReadOnly(code);
    }
    public void SetGroupReadOnly(string code)
    { 
        this.UserSelect.SetTBGroupReadOnly(code);
    }
    protected void FillGirdView()
    {
        gridView.ShowFooter = false;
        gridView.DataSource = SessionManager.DataSet.Tables[m_TableName];
        gridView.DataBind();
        gridView.Columns[4].Visible = Convert.ToBoolean(hfShowWorkTime.Value);
        gridView.Columns[6].Visible = !IsReadOnly;
    }

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        { 
            (e.Row.Cells[4].Controls[1] as TextBox).ReadOnly = this.IsReadOnly;
            (e.Row.Cells[5].Controls[1] as TextBox).ReadOnly = this.IsReadOnly;
            e.Row.Cells[6].Attributes.Add("onclick", "return confirm('确认要删除吗？');");
        }
    }
    protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string ID = (gridView.Rows[e.RowIndex].Cells[5].Controls[3] as HiddenField).Value;
        StringBuilder str = new StringBuilder();
        foreach (DataRow row in SessionManager.DataSet.Tables[m_TableName].Rows)
        {
            if (row.RowState != DataRowState.Deleted && ID.Equals(row["UserID"].ToString()))
            {
                str.Append(",'").Append(row["UserID"].ToString()).Append("'");
                row.Delete();
                FillGirdView();
                break;
            }
        }
        if (str.Length > 0)
        {
            //PMSAccess.ExecuteNonQuery(this.Connection, "update PMS_User set IsWorking='" + UserStatus.Waiting + "' where UserId in (" + str.Remove(0, 1).ToString() + ")");
        }
    }
}
